var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();
var routes = require('./routes');
var apiAuthTokenMiddleware = require('./middleware/apiAuthTokenMiddleware')
var stationOpenMiddleware = require('./middleware/StationOpenMiddleware')
var jsonUti = require('./utils/json')
var utils = require('./utils/Common')

require('dotenv').config();

var cors = require('cors')

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));

//自定义中间件
app.use(jsonUti);




app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: err });
});



app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors({
  origin:"*",
  method:['GET','POST'],
}));

//路由中间件
app.use(apiAuthTokenMiddleware);
//路由中间件
//app.use(stationOpenMiddleware);

//导入路由
app.use('/api', routes);








//设置允许跨域

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
